// 导入组件
import Vue from 'vue'
import VueRouter from 'vue-router'
import storage from 'store'
import store from '../vuex/index'
import menuNav from './menuNav'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

// 启用路由
Vue.use(VueRouter)

var routes = [
	{
		path: '/',
		redirect: '/login'
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login')
	},
	{
		path: '/404',
		name: '404',
		component: () => import('@/views/errorPage/404')
	},
	...menuNav
]

// 导出路由
const router = new VueRouter({
	mode: 'hash',
	routes
})

// 登陆页面
const loginRoutePath = '/login'
// 路由拦截器
router.beforeEach((to, from, next) => {
	NProgress.configure({ showSpinner: false }); // 关闭Nprogress自动触发
	if(to.meta.title) NProgress.start(); // 开启NProgress
	// 获取 token
	const token = storage.get('logintoken')
	// token 为空 并且 跳转的路径不是登陆页面
	if (!token && to.path !== loginRoutePath) {
		// 跳转登陆页面
		next({ path: loginRoutePath, replace: true })
	} else if (token) {
		if (to.path === loginRoutePath) {
			next({ path: store.state.defaultPath })
		} else {
			next()
		}
	} else {
		next()
	}
})

// 路由加载后
router.afterEach(() => {
	NProgress.done();
})

// export function initDynamicRoutes() {
// 	const currentRoutes = router.options.routes;
// 	const rightList = store.state.rightList;
// 	rightList.forEach(item => {
// 		item.children.forEach(item => {
// 			currentRoutes[2].children.push(ruleMapping[item.path])
// 		})
// 	}) 
// 	router.addRoutes(currentRoutes)
// }


// 导出路由
export default router
